
#include "dump_pts.h"
#include "SDL.h"

#include <stdio.h>
#include <sys/time.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <stdio.h>
#include <stdarg.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>



FILE *ptsfile = NULL;
SDL_mutex *ptsmutex;

void dump_pts_init(int isdump)
{
    ptsmutex = SDL_CreateMutex();
    if (isdump > 0) {
        ptsfile = fopen("./dump_pts.txt", "w");
    } else {

    }
}

void dump_pts_close()
{
    if (ptsfile) {
        fclose(ptsfile);
    }
    SDL_DestroyMutex(ptsmutex);
}

static int64_t get_cur_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    int64_t time = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
    return time;
}

static void dump_pts(char* source, double pts, int serial)
{
    struct timeval current;
    gettimeofday(&current, NULL);

    struct tm stime;
    localtime_r(&current.tv_sec, &stime);

    char LOGContent[4096] = {0};
    sprintf(LOGContent, "%s:%lld:pts:%lf:serial:%d\n",
            source, get_cur_ms(), pts, serial);
    SDL_LockMutex(ptsmutex);
    fwrite(LOGContent, strlen(LOGContent), 1, ptsfile);
    SDL_UnlockMutex(ptsmutex);
}

void dump_apts(double pts, int serial)
{
    char source[] = "audio";
    dump_pts(source, pts, serial);
}

void dump_vpts(double pts, int serial)
{
    char source[] = "video";
    dump_pts(source, pts, serial);
}

void dump_set_clock(double pts, int serial)
{
    char source[] = "set";
    dump_pts(source, pts, serial);
}
